package com.tianji.learning.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.api.client.user.UserClient;
import com.tianji.api.dto.user.UserDTO;
import com.tianji.common.domain.dto.PageDTO;
import com.tianji.common.exceptions.BizIllegalException;
import com.tianji.common.exceptions.CommonException;
import com.tianji.common.exceptions.DbException;
import com.tianji.common.utils.*;
import com.tianji.learning.domain.InteractionQuestion;
import com.tianji.learning.domain.InteractionReply;
import com.tianji.learning.domain.dto.QuestionFormDTO;
import com.tianji.learning.domain.query.QuestionPageQuery;
import com.tianji.learning.domain.vo.QuestionVO;
import com.tianji.learning.enums.QuestionStatus;
import com.tianji.learning.mapper.InteractionQuestionMapper;
import com.tianji.learning.service.InteractionQuestionService;
import com.tianji.learning.service.InteractionReplyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
* @author 阿娇的秘密星球
* @description 针对表【interaction_question(互动提问的问题表)】的数据库操作Service实现
* @createDate 2024-12-27 11:35:59
*/
@Service
public class InteractionQuestionServiceImpl extends ServiceImpl<InteractionQuestionMapper, InteractionQuestion>
    implements InteractionQuestionService{



    @Override
    public void addQuestion(QuestionFormDTO dto) {
        InteractionQuestion interactionQuestion = BeanUtils.copyBean(dto, InteractionQuestion.class);
        interactionQuestion.setStatus(QuestionStatus.UN_CHECK.getValue());
        interactionQuestion.setUserId(UserContext.getUser());
        boolean b = this.save(interactionQuestion);
        if(!b){
            throw new DbException("新增问题失败");
        }
    }

    @Override
    public void updateQuestion(QuestionFormDTO dto, Long id) {
        InteractionQuestion interactionQuestion = this.getById(id);
        if (interactionQuestion==null){
            throw new CommonException("问题不存在");
        }
        boolean b = this.lambdaUpdate()
                .set(InteractionQuestion::getTitle, dto.getTitle())
                .set(InteractionQuestion::getDescription, dto.getDescription())
                .set(InteractionQuestion::getAnonymity, dto.getAnonymity())
                .eq(InteractionQuestion::getId, id)
                .update();
        if(!b){
            throw new DbException("修改问题失败");
        }

    }
    @Autowired
    private UserClient userClient;

    @Override
    public QuestionVO getDetailById(Long id) {
        InteractionQuestion interactionQuestion = this.lambdaQuery().eq(InteractionQuestion::getId, id).one();
        if(interactionQuestion==null || interactionQuestion.getHidden()){
            return null;
        }
        UserDTO user = userClient.queryUserById(interactionQuestion.getUserId());
        QuestionVO questionVO = BeanUtils.copyBean(interactionQuestion, QuestionVO.class);
        //不为匿名
        if(!questionVO.getAnonymity()){
            questionVO.setUserIcon(user.getIcon());
            questionVO.setUserName(user.getName());
        }
        return questionVO;
    }

    @Autowired
    private InteractionReplyService replyService;
    /**
     * 用户端分页查询问题
     * @param questionPageQuery
     * @return
     */
    @Override
    public PageDTO<QuestionVO> queryPage(QuestionPageQuery questionPageQuery) {
        if (questionPageQuery.getSectionId()==null && questionPageQuery.getCourseId()==null){
            throw new BizIllegalException("参数不正确");
        }
        Page<InteractionQuestion> page = lambdaQuery().select(InteractionQuestion.class, q -> !"description".equals(q.getProperty()))
                .eq(BooleanUtils.isTrue(questionPageQuery.getOnlyMine()), InteractionQuestion::getUserId, UserContext.getUser())
                .eq(ObjectUtils.isNotEmpty(questionPageQuery.getCourseId()), InteractionQuestion::getCourseId, questionPageQuery.getCourseId())
                .eq(ObjectUtils.isNotEmpty(questionPageQuery.getSectionId()), InteractionQuestion::getSectionId, questionPageQuery.getSectionId())
                .eq(InteractionQuestion::getHidden, false)
                .page(questionPageQuery.toMpPageDefaultSortByCreateTimeDesc());
        List<InteractionQuestion> records = page.getRecords();
        if (CollUtils.isEmpty(records)){
            throw new CommonException("集合为空");
        }
        Set<Long> userIdSet = records.stream().map(InteractionQuestion::getUserId).collect(Collectors.toSet());
        Set<Long> answerIdSet = records.stream().map(InteractionQuestion::getLatestAnswerId)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());
        Map<Long, InteractionReply> answerMap=new HashMap<>();
        if (CollUtils.isNotEmpty(answerIdSet)){
            List<InteractionReply> answerList = replyService.listByIds(answerIdSet);
            answerMap = answerList.stream().collect(Collectors.toMap(InteractionReply::getId, i -> i));
            Set<Long> answerUserIdSet = answerList.stream().map(InteractionReply::getUserId).collect(Collectors.toSet());
            userIdSet.addAll(answerUserIdSet);
        }
        List<UserDTO> userList = userClient.queryUserByIds(userIdSet);
        Map<Long, UserDTO> userMap = userList.stream().collect(Collectors.toMap(UserDTO::getId, u -> u));
        List<QuestionVO> voList=new ArrayList<>();
        for (InteractionQuestion record : records) {
            QuestionVO vo = BeanUtils.copyBean(record, QuestionVO.class);
            voList.add(vo);
            if (!record.getAnonymity()){
                UserDTO user = userMap.getOrDefault(record.getUserId(), new UserDTO());
                vo.setUserName(user.getName());
                vo.setUserIcon(user.getIcon());
            }
            InteractionReply reply = answerMap.getOrDefault(record.getLatestAnswerId(), new InteractionReply());
            vo.setLatestReplyContent(reply.getContent());
            if (!reply.getAnonymity()){
                UserDTO replyUser = userMap.getOrDefault(reply.getUserId(), new UserDTO());
                vo.setLatestReplyUser(replyUser.getName());
            }
        }
        return PageDTO.of(page,voList);

    }

    /**
     * 删除我的问题
     * @param id
     */
    @Override
    public void deleteQuestionById(Long id) {
        InteractionQuestion interactionQuestion = this.getById(id);
        if(interactionQuestion==null){
            throw new CommonException("问题不存在");
        }
        boolean remove = this.removeById(id);
        if (!remove){
            throw new DbException("删除问题失败");
        }
    }

}




